import { Request, Response, NextFunction } from 'express';
import { prisma } from '../../config/database';
import { BaseController } from '../../utils/autoBind';
import { ResponseUtils } from '../../utils/responseUtils';
import { BUSINESS_ERROR_CODES } from '../../utils/errorCodes';

export class ClientArtistController extends BaseController {
  // 获取艺人列表
  async getArtistList(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { page = 1, limit = 10, status } = req.query;
      const skip = (Number(page) - 1) * Number(limit);

      const where: any = {};
      if (status) where.status = status;

      const [artists, total] = await Promise.all([
        prisma.artist.findMany({
          where,
          skip: skip,
          take: Number(limit),
          orderBy: { createdAt: 'desc' },
          select: {
            id: true,
            name: true,
            description: true,
            avatar: true,
            bannerImage: true,
            country: true,
            status: true,
            createdAt: true
          }
        }),
        prisma.artist.count({ where })
      ]);

      ResponseUtils.success(res, {
        items: artists,
        pagination: {
          total,
          page: Number(page),
          limit: Number(limit),
          totalPages: Math.ceil(total / Number(limit))
        }
      }, '获取艺人列表成功');
    } catch (error) {
      next(error);
    }
  }

  // 获取艺人详情
  async getArtistDetail(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;

      const artist = await prisma.artist.findUnique({
        where: { id: Number(id) },
        select: {
          id: true,
          name: true,
          description: true,
          avatar: true,
          bannerImage: true,
          country: true,
          status: true,
          createdAt: true,
          works: {
            where: { isRepresentative: true },
            select: {
              id: true,
              title: true,
              duration: true,
              description: true,
              releaseDate: true
            },
            orderBy: { releaseDate: 'desc' }
          }
        }
      });

      if (!artist) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.ARTIST_NOT_FOUND, '艺人不存在');
        return;
      }

      ResponseUtils.success(res, artist, '获取艺人详情成功');
    } catch (error) {
      next(error);
    }
  }

  // 获取艺人演出
  async getArtistPerformances(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      const { page = 1, limit = 10 } = req.query;
      const skip = (Number(page) - 1) * Number(limit);

      // 检查艺人是否存在
      const artist = await prisma.artist.findUnique({
        where: { id: Number(id) }
      });

      if (!artist) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.ARTIST_NOT_FOUND, '艺人不存在');
        return;
      }

      const [performances, total] = await Promise.all([
        prisma.performance.findMany({
          where: { artistId: Number(id) },
          skip: skip,
          take: Number(limit),
          orderBy: { startTime: 'asc' },
          select: {
            id: true,
            title: true,
            description: true,
            venue: true,
            floor: true,
            startTime: true,
            endTime: true,
            status: true
          }
        }),
        prisma.performance.count({ where: { artistId: Number(id) } })
      ]);

      ResponseUtils.success(res, {
        items: performances,
        pagination: {
          total,
          page: Number(page),
          limit: Number(limit),
          totalPages: Math.ceil(total / Number(limit))
        }
      }, '获取艺人演出成功');
    } catch (error) {
      next(error);
    }
  }

  // 获取艺人作品
  async getArtistWorks(req: Request, res: Response, next: NextFunction): Promise<void> {
    try {
      const { id } = req.params;
      const { page = 1, limit = 10 } = req.query;
      const skip = (Number(page) - 1) * Number(limit);

      // 检查艺人是否存在
      const artist = await prisma.artist.findUnique({
        where: { id: Number(id) }
      });

      if (!artist) {
        ResponseUtils.sendError(res, BUSINESS_ERROR_CODES.ARTIST_NOT_FOUND, '艺人不存在');
        return;
      }

      const [works, total] = await Promise.all([
        prisma.artistWork.findMany({
          where: { artistId: Number(id) },
          skip: skip,
          take: Number(limit),
          orderBy: { releaseDate: 'desc' },
          select: {
            id: true,
            title: true,
            description: true,
            duration: true,
            releaseDate: true,
            isRepresentative: true,
            createdAt: true
          }
        }),
        prisma.artistWork.count({ where: { artistId: Number(id) } })
      ]);

      ResponseUtils.success(res, {
        items: works,
        pagination: {
          total,
          page: Number(page),
          limit: Number(limit),
          totalPages: Math.ceil(total / Number(limit))
        }
      }, '获取艺人作品成功');
    } catch (error) {
      next(error);
    }
  }
}